import java.util.ArrayList;
import java.util.List;
import java.util.Random;

class ElementSpawner {
    private final List<GameElementFactory> factories;
    private float totalWeight;
    private final Random random;

    public ElementSpawner() {
        this.factories = new ArrayList<>();
        this.totalWeight = 0;
        this.random = new Random();
    }

    public void addFactory(GameElementFactory factory) {
        factories.add(factory);
        totalWeight += factory.getSpawnWeight();
    }

    public GameElement spawnElement(int x, int y) {
        float r = random.nextFloat() * totalWeight;
        float cumulativeWeight = 0;

        for (GameElementFactory factory : factories) {
            cumulativeWeight += factory.getSpawnWeight();
            if (r <= cumulativeWeight) {
                return factory.createElement(x, y);
            }
        }

        return null;
    }
}
